package com.yuzhihao.writejvm.attributes;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * The LineNumberTable attribute is an optional variable-length attribute in the attributes table of a Code attribute (§4.7.3). It may be used by debuggers to determine which part of the code array corresponds to a given line number in the original source file.
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.12">LineNumberTableAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日11:51:06
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class LineNumberTableAttribute extends Attributes {

    private int line_number_table_length_u2 = 2;

    private int line_number_table_length;

    private List<Line> lines = new ArrayList<>();

    public LineNumberTableAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.line_number_table_length = Parse.byteToInt(this.line_number_table_length_u2, dis);

            int i = 0;
            while (i < this.line_number_table_length){
                Line line = new Line();
                line.parse(dis,ci);
                this.lines.add(line);
                i++;
            }
        } catch (IOException e) {
            log.error(e);
        }
    }

    @Override
    public String print(String print) {
        StringBuilder builder = new StringBuilder();
        builder.append(print).append("LineNumberTable").append(PrintFormat.COLON).append(System.lineSeparator());

        for (Line line : this.lines) {
            builder.append(print).append(PrintFormat.EMPTY);
            builder.append(line);
            builder.append(System.lineSeparator());
        }
        return builder.toString();
    }

    @Data
    @Log4j2
    public static class Line implements Parse{
        private int start_pc_u2 = 2;
        private int start_pc;

        private int line_number_u2 = 2;
        private int line_number;

        @Override
        public void parse(DataInputStream dis, ClassInfo ci) {
            try {
                this.start_pc = Parse.byteToInt(this.start_pc_u2, dis);
                this.line_number = Parse.byteToInt(this.line_number_u2, dis);
            } catch (IOException e) {
                log.error(e);
            }
        }

        @Override
        public String toString() {
            return "line"+PrintFormat.EMPTY+this.line_number+PrintFormat.COLON+PrintFormat.EMPTY+this.start_pc;
        }
    }

}
